package com.seek.inter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.seek.cache.CacheUtil;
import com.seek.common.handler.SpringContextHolder;
import com.seek.inter.interdto.InterDtoUser;
import com.seek.model.dto.ResultInfo;
import com.seek.service.CustomerService;
import com.seek.service.ReadService;
import com.seek.util.CommonUtil;

/**
 * 本类主要是作为客户实名认证审核相关接口实现类
 *
 */
public class CustomerVerifyWebInter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private CustomerService customerService = (CustomerService)SpringContextHolder.getBean("customerService");
	private ReadService readService = (ReadService)SpringContextHolder.getBean("readService");

	/**
	 * 获取客户实名认证列表：只能查询最近30天申请认证的信息
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getCertityList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String auditStatus = reqJson.getString("auditStatus");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		int ageQ = CommonUtil.getIntValue(reqJson.getString("ageQ"));
		int ageZ = CommonUtil.getIntValue(reqJson.getString("ageZ"));

		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and a.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(auditStatus)){
			where.append(" and b.audit_status=?");
			params.add(CommonUtil.getIntValue(auditStatus));
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and b.submit_time > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and b.submit_time < ?");
			params.add(rqz);
		}
		if (ageQ>0){
			where.append(" and a.age >= ?");
			params.add(ageQ);
		}
		if (ageZ>0){
			where.append(" and a.age <= ?");
			params.add(ageZ);
		}

		// 取得总记录行数
		String sql = "select count(1) cnt from t_customer a, t_customer_certify b where a.id=b.customer_id and a.company_id=? and b.submit_time>date_sub(curdate(),interval 1 day)"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb = new StringBuffer("select a.id custId,REPLACE(a.phone_no, SUBSTR(a.phone_no,4,4), '****') custPhone,a.name custName,a.age,a.reg_date regDate,b.submit_time submitTime,");
		else
			sb = new StringBuffer("select a.id custId,a.phone_no custPhone,a.name custName,a.age,a.reg_date regDate,b.submit_time submitTime,");
		sb.append(" b.audit_status auditStatus,b.audit_time auditTime,a.id custId,")
		  .append(" (select u.user_name from t_sys_user u where u.id=b.audit_id) auditName")
		  .append(" from t_customer a, t_customer_certify b where a.id=b.customer_id and a.company_id=?")
		  .append(" and b.submit_time>date_sub(curdate(),interval 1 day)")
		  .append(where.toString()).append(" order by b.submit_time asc");

		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}

	/**
	 * 获取客户实名认证详情
	 * @param request
	 * @param reqJson
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getCertifyDetail(HttpServletRequest request, JSONObject reqJson) throws Exception{
		ResultInfo result = new ResultInfo();
		Long custId = reqJson.getLong("custId");

		try{
			if (custId == null || custId < 1) {
				result.setStatus(1);
				result.setMessage("参数错误，请检查!");
				return result;
			}

			StringBuffer sb = new StringBuffer("select a.id custId,a.phone_no custPhone,a.name custName,a.age,a.sex, ");
			sb.append(" a.card_number cardNumber,b.reg_city regCity,b.card_city cardCity,")
			  .append(" b.img_1 img1,b.img_2 img2,b.img_3 img3,b.audit_status auditStatus,b.audit_remark auditRemark")
			  .append(" from t_customer a, t_customer_certify b")
			  .append(" where a.id=b.customer_id and a.id=?");
			result.setStatus(0);
			result.setMessage("成功");
			result.setBody(readService.findOneMapBySql(sb.toString(), new Object[]{custId}));
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}

	/**
	 * 客户实名认证审核
	 * @param request
	 * @param reqJson
	 * @return
	 * @throws Exception
	 */
	public ResultInfo certifyAudit(HttpServletRequest request, JSONObject reqJson) throws Exception{
		ResultInfo result = new ResultInfo();
		Long custId = reqJson.getLong("custId");
		int auditStatus = CommonUtil.getIntValue(reqJson.getString("auditStatus"));
		String auditRemark = reqJson.getString("auditRemark");
		String _currnetUserId = reqJson.getString("_currnetUserId");
		try{
			if (custId == null || custId<1 || auditStatus<1 || (auditStatus==2 && CommonUtil.isEmpty(auditRemark))) {
				result.setStatus(1);
				result.setMessage("参数错误，请检查!");
				return result;
			}

			customerService.certifyAudit(custId, _currnetUserId, auditStatus, auditRemark);

			result.setStatus(0);
			result.setMessage("成功");
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}

	/**
	 * 获取客户银行卡绑定列表：只取最近30天数据，并且只检索客户当前绑定，剔除历史绑定数据
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getCardBindList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String auditStatus = reqJson.getString("auditStatus");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");

		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and a.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(auditStatus)){
			where.append(" and b.audit_status=?");
			params.add(CommonUtil.getIntValue(auditStatus));
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and b.submit_time > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and b.submit_time < ?");
			params.add(rqz);
		}

		// 取得总记录行数
		String sql = "select count(1) cnt from t_customer a, t_customer_card b where a.id=b.customer_id and b.history=0 and a.company_id=? and b.submit_time>date_sub(curdate(),interval 30 day)"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb = new StringBuffer("select a.id,REPLACE(a.phone_no, SUBSTR(a.phone_no,4,4), '****') custPhone,a.name custName,b.bank_name bankName,b.card_number cardNumber,b.bank_phone bankPhone,");
		else
			sb = new StringBuffer("select a.id custId,a.phone_no custPhone,a.name custName,b.bank_name bankName,b.card_number cardNumber,b.bank_phone bankPhone,");
		sb.append(" b.submit_time submitTime,b.audit_status auditStatus,b.audit_time auditTime,b.audit_remark auditRemark,")
		  .append(" (select u.user_name from t_sys_user u where u.id=b.audit_id) auditName,a.id custId")
		  .append(" from t_customer a, t_customer_card b where a.id=b.customer_id and b.history=0 and a.company_id=? and b.submit_time>date_sub(curdate(),interval 30 day)")
		  .append(where.toString()).append(" order by b.submit_time asc");

		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}

	/**
	 * 获取客户花呗认证列表：只取最近30天数据，并且只检索客户当前绑定，剔除历史绑定数据
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getZfbCertifyList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String auditStatus = reqJson.getString("auditStatus");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		String userId= reqJson.getString("_currnetUserId");
		String token = reqJson.getString("token");

		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and a.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(auditStatus)){
			where.append(" and b.audit_status=?");
			params.add(CommonUtil.getIntValue(auditStatus));
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and b.submit_time > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and b.submit_time < ?");
			params.add(rqz);
		}
		InterDtoUser user = CacheUtil.getLoginCache(token);
		if (user!=null && user.getIsAdmin() != 1){
			where.append(" and b.audit_id=?");
			params.add(userId);
		}

		// 取得总记录行数
		String sql = "select count(1) cnt from t_customer a, t_customer_zfb b where a.id=b.customer_id and b.lsbz=0 and a.company_id=? and b.submit_time>date_sub(curdate(),interval 30 day)"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb = new StringBuffer("select a.id custId,REPLACE(a.phone_no, SUBSTR(a.phone_no,4,4), '****') custPhone,a.name custName,b.login_name loginName,b.login_pwd loginPwd,b.zfb_credit zfbCredit,");
		else
			sb = new StringBuffer("select a.id custId,a.phone_no custPhone,a.name custName,b.login_name loginName,b.login_pwd loginPwd,b.zfb_credit zfbCredit,");
		sb.append(" b.submit_time submitTime,b.audit_status auditStatus,b.audit_time auditTime,b.audit_remark auditRemark,")
				.append(" (select u.user_name from t_sys_user u where u.id=b.audit_id) auditName,a.id custId")
				.append(" from t_customer a, t_customer_zfb b where a.id=b.customer_id and b.lsbz=0 and a.company_id=? and b.submit_time>date_sub(curdate(),interval 30 day)")
				.append(where.toString()).append(" order by b.submit_time asc");

		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}

	/**
	 * 支付宝审核
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo zfbCertifyAudit(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long custId = reqJson.getLong("custId");
		int auditStatus = CommonUtil.getIntValue(reqJson.getLong("auditStatus"));
		int zfbCredit = CommonUtil.getIntValue(reqJson.getString("zfbCredit"));
		String auditRemark = reqJson.getString("auditRemark");
		String userId = reqJson.getString("_currnetUserId");

		if(companyId == null || companyId<1 || custId == null || custId < 1 || auditStatus<1 || (auditStatus==1 && zfbCredit<1)) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}
		customerService.zfbAudit(custId, userId, auditStatus, auditRemark, zfbCredit);

		result.setStatus(0);
		result.setMessage("成功");
		return result;
	}

	/**
	 * 客户通讯录
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getAddrbookList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		if (CommonUtil.isEmpty(custPhone) || custPhone.length() != 11){
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}

		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			where.append(" and a.phone_no = ?");
			params.add(custPhone);
		}

		// 取得总记录行数
		String sql = "select count(1) cnt from t_customer a, t_customer_addrbook b where a.id=b.customer_id and a.company_id=?"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("select a.phone_no custPhone,a.name custName,b.phone_no phoneNo,b.phone_name phoneName,b.calls_number callsNumber");
		sb.append(" from t_customer a, t_customer_addrbook b where a.id=b.customer_id and a.company_id=?")
		  .append(where.toString()).append(" order by b.addr_type asc,b.is_realtive desc,b.calls_number desc");

		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}

	/**
	 * 客户管理->获取客户列表：如果是贷款审核员或者是催收员只能看他当前待审或待催客户
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getCustomerList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String status = reqJson.getString("status");
		String token = reqJson.getString("token");

		InterDtoUser user = CacheUtil.getLoginCache(token);
		if (user == null){
			result.setStatus(1);
			result.setMessage("用户未登录或登录已失效！");
			return result;
		}

		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and a.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(status)){
			where.append(" and a.status=?");
			params.add(status);
		}
		if (user.getIsAudit() == 1){
			where.append(" and exists (select 1 from t_loan b where a.id=b.customer_id and b.loan_status=0 and b.auditor_id=?)");
			params.add(user.getId());
		}
		if (user.getIsOverduer() == 1){
			where.append(" and exists (select 1 from t_loan b where a.id=b.customer_id and  b.loan_status in (3,6) and b.overduer_id=?)");
			params.add(user.getId());
		}

		// 取得总记录行数
		String sql = "select count(1) cnt from t_customer a where a.company_id=?"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb = new StringBuffer("select a.id custId,REPLACE(a.phone_no, SUBSTR(a.phone_no,4,4), '****') custPhone,a.name custName,a.status,a.is_black isBlack,");
		else
			sb = new StringBuffer("select a.id custId,a.phone_no custPhone,a.name custName,a.status,a.is_black isBlack,");
		sb.append(" a.reg_date regDate,a.authed_date authedDate,a.authed_credit authedCredit,")
		  .append(" (select b.zfb_credit from t_customer_zfb b where b.customer_id=a.id and b.lsbz=0 and b.audit_status=1) zfbCredit,")
		  .append(" (select count(1) from t_loan b where b.customer_id=a.id) loanNum,")
		  .append(" (select ifnull(sum(case when ifnull(b.payback_date,now())>b.end_time then 1 else 0 end),0) from t_loan b where b.customer_id=a.id) overTimeNum,")
		  .append(" (select count(1) from t_loan_overdue_log b where b.customer_id=a.id) overdueLogNum")
		  .append(" from t_customer a where a.company_id=?")
		  .append(where.toString()).append(" order by a.id desc");

		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}

	/**
	 * 客户管理->获取指定客户的货款记录列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getCustLoanList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long custId = reqJson.getLong("custId");

		// 拼接检索条件
		List<Object> params = new ArrayList<Object>();
		params.add(custId);

		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan a where a.customer_id=?";
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("select a.id loanId,a.req_money reqMoney,a.start_time,a.end_time endTime,a.loan_status loanStatus,");
		sb.append(" a.payback_date paybackTime,(case when a.loan_status in (3,5,6) and ifnull(a.payback_date,now())>a.end_time then 1 else 0 end) isOverdue,")
		  .append(" a.late_fee lateFee,a.off_latefee offLatefee,")
		  .append(" (select count(1) from t_loan_overdue_log b where b.loan_id=a.id) overdueLogs")
		  .append(" from t_loan a where a.customer_id=? order by a.id desc");

		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}

	/**
	 * 客户管理->获取指定客户的催收记录列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getCustOverdueList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long custId = reqJson.getLong("custId");
		Long loanId = reqJson.getLong("loanId");

		// 拼接检索条件
		List<Object> params = new ArrayList<Object>();
		params.add(custId);
		StringBuffer where = new StringBuffer("");
		if (loanId != null && loanId>0){
			where.append(" and a.loan_id=?");
			params.add(loanId);
		}

		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan_overdue_log a,t_loan b where a.loan_id=b.id and a.customer_id=?"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("select b.id loanId,b.req_money reqMoney,b.start_time startTime,b.end_time endTime,");
		sb.append(" a.create_time createTime,a.remark,(select u.user_name from t_sys_user u where u.id=a.creator_id) createUserName,a.next_overdue_time nextOverdueTime")
		  .append(" from t_loan_overdue_log a,t_loan b where a.loan_id=b.id and a.customer_id=?").append(where.toString()).append(" order by a.id desc");

		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}

	/**
	 * 客户拉黑或洗白
	 * @param request
	 * @param reqJson
	 * @return
	 * @throws Exception
	 */
	public ResultInfo setCustBlackState(HttpServletRequest request, JSONObject reqJson) throws Exception{
		ResultInfo result = new ResultInfo();
		Long custId = reqJson.getLong("custId");
		int isBlack = CommonUtil.getIntValue(reqJson.getString("isBlack"));

		try{
			if (custId == null || custId<1) {
				result.setStatus(1);
				result.setMessage("参数错误，请检查!");
				return result;
			}

			customerService.setCustBlack(custId, isBlack);
			result.setStatus(0);
			result.setMessage("成功");
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}

	/**
	 * 查看短信发送记录:只取最近60天的短信
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getSmsLog(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		String custPhone = reqJson.getString("custPhone");
		Long companyId = reqJson.getLong("companyId");
		int smsType = CommonUtil.getIntValue(reqJson.getString("smsType"));

		// 拼接检索条件
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		StringBuffer where = new StringBuffer("");
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and a.phone_no like ?");
			params.add(custPhone);
		}
		if (smsType>0){
			where.append(" and a.msg_type=?");
			params.add(smsType);
		}

		// 取得总记录行数
		String sql = "select count(1) cnt from t_sms_log a where a.company_id=? and a.create_time>date_sub(curdate(),interval 60 day)"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("select a.phone_no phoneNo,a.verif_code verficationCode,a.create_time createTime,a.msg_type smsType ");
		sb.append(" from t_sms_log a where a.company_id=? and a.create_time>date_sub(curdate(),interval 60 day)")
		  .append(where.toString()).append(" order by a.id desc");

		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}

  /**
   * 获取客户运营商认证详情
   */
  public ResultInfo getCarrierDetail(HttpServletRequest request, JSONObject reqJson)
      throws Exception {
    ResultInfo result = new ResultInfo();
    Long custId = reqJson.getLong("custId");
    Map<String, Object> data = new HashMap<>();
    try {
      if (custId == null || custId < 1) {
        result.setStatus(1);
        result.setMessage("参数错误，请检查!");
        return result;
      }
			String customerSql = "select a.company_id as companyId, ifnull(a.name,'') as name ,"
					+ "ifnull(a.phone_no,'') as phoneNo,ifnull(a.sex,-1) as sex ,ifnull(a.age,-1) as age,"
					+ "ifnull(a.card_number,'') as cardNo,ifnull(b.reg_city,'') as regCity,"
					+ "ifnull(b.card_city,'') as cardCity,ifnull(b.img_1,'')"
					+ " as frontImg,ifnull(b.img_2,'') as backImg from t_customer a left join "
					+ "t_customer_certify b on a.id=b.customer_id where a.id = ? limit 1";

			String carrierSql = "select ifnull(name,'') as name,ifnull(carrier,'') as carrier,"
					+ "ifnull(state,'-1')  as state,ifnull(province,'')  as province,ifnull(city,'')  as city,"
					+ "ifnull(open_time,-1) as openTime,ifnull(package_name,'') as packageName "
					+ "from t_customer_mobile_info where company_id = ? and customer_id = ?";
			String billSql = "select ifnull(bill_month,'') as billMonth,ifnull(bill_amount,0) as billAmount "
					+ "from t_customer_mobile_bill where company_id = ? and customer_id = ? and deleted = ? "
					+ "order by bill_month desc ";
			String metricSql = "select ifnull(metric_desc,'') as metricDesc,ifnull(metric_value,'') "
					+ "as metricValue,ifnull(score,'') as  score from t_customer_metric a ,t_auth_rule b  "
					+ "where a.auth_rule_id = b.id and a.company_id = ? and a.customer_id = ?  "
					+ "and a.deleted = ? and b.auth_prdouct = ?";

      Map<String, Object> customerInfo = readService.findOneMapBySql(customerSql, custId);
      data.put("customerInfo", customerInfo);
      if (MapUtils.isNotEmpty(customerInfo)) {
        Long companyId = CommonUtil.getLongValue(customerInfo.get("companyId"));
        Map<String, Object> carrierInfo = readService
            .findOneMapBySql(carrierSql, new Object[]{companyId, custId});
        if(MapUtils.isEmpty(carrierInfo)){
					carrierInfo = new HashMap<>();
				}
				data.put("carrierInfo", carrierInfo);
				List billInfo = readService.findMapBySql(billSql,new Object[]{companyId, custId,0});
        data.put("billInfo", billInfo);

				List metricInfo = readService.findMapBySql(metricSql,new Object[]{companyId, custId,0,"CARRIER"});
        data.put("metricInfo", metricInfo);
				result.setStatus(0);
        result.setMessage("成功");
        result.setBody(data);
        return result;
      }else{
        result.setStatus(1);
        result.setMessage("没有查询到客户基本信息");
        return result;
      }



    } catch (Exception e) {
      logger.error("系统异常", e);
      result.setStatus(1);
      result.setMessage(e.getMessage());
      return result;
    }
  }
  
  	/**
	 * 货款审核员申请货款审核任务
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public synchronized ResultInfo reqZfbAudit(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		int num = CommonUtil.getIntValue(reqJson.getLong("num"));	
		String userId = reqJson.getString("_currnetUserId");
		
		if(companyId == null || companyId<1 || num < 1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		} 
		String sql = "update t_customer_zfb set audit_id=? where company_id=? and audit_status=0 and audit_id is null order by id asc limit ?";
		customerService.executeUpdate(sql, new Object[]{userId,companyId,num});
				
		result.setStatus(0);
		result.setMessage("成功");
		return result;
	}
}
